// TODO add auto match support
/**
---首先浏览器安装好油猴脚本插件，点击加号标签打开新建页面，清空里面所有内容，将本文内容复制并粘贴上去，关闭并保存---
1.登入网页版网易云音乐
2.转到搜索页面
3.在文本框中导入如下示例数据格式数据：
[{"title":"The Road to Life","artist":"Monocle Twins","album":"The Road To Life","dura":"3:51"},
{"title":"Adrift","artist":"Cooper Sams","album":"Adrift","dura":"2:38"},
{"title":"Pretending","artist":"Evolution of Stars","album":"Pretending","dura":"3:06"},
{"title":"Glaciers","artist":"Lights & Motion","album":"Bloom","dura":"2:56"},
{"title":"As the Lights Fade Away","artist":"The Echelon Effect","album":"Atlantic","dura":"1:46"},
{"title":"Fusion","artist":"Eroded Sky","album":"Fusion","dura":"3:47"},
{"title":"We Are Forever","artist":"They Dream By Day","album":"Limbo","dura":"2:14"}]
其中title是歌名，artist是歌手名，album是专辑名
4.点击“加载”按钮 --> 点击“搜索”按钮，如没搜索到将自动将当前曲目加入到未找到列表（点左上角红点打开）
--> 点击“导入到”按钮，将自动选取第一条搜索结果，并弹出预先建好的歌单列表 --> 点击相应歌单后导入
**/
// ==UserScript==
// @name         网易云音乐歌单导入助手
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  try to take over the world!
// @author       icdcom
// @match        *://music.163.com/
// @match        *://www.xiami.com/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

//TODO arrPinter brokes and need fixing;
(function () {
  "use strict";


  let siteTitle = "";
  let tracks = [];
  let totalTracks = 0;
  let currentTrack = null;
  let trackCache = [];
  let tracksNotFound = [];
  // Is all the elements in the track array passed once
  let isLooping = false;
  // are the track control buttons controlling the the contents in the track arrays
  let isCtrlBtn = false;
  let mutationObserver = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
      // If the appropriate dom changes have occured and the search list is empty
      if (
        mutation.type == "childList" &&
        mutation.addedNodes &&
        mutation.addedNodes.length > 0 &&
        mutation.addedNodes[0].className &&
        mutation.addedNodes[0].className == "n-nmusic" &&
        !isLooping
      ) {
        tracksNotFound.push(currentTrack);
        window.nf.innerText = tracksNotFound.length;
      }
    });
  });

  function initCmp() {
    siteTitle = document.querySelector("title").text;
    if (/网易云音乐/g.test(siteTitle)) {
      // The iframe that wraps the whole search panel
      window.doc = document.getElementById("g_iframe").contentWindow.document;
      window.srchBtn = window.doc.querySelector(".btn.j-flag");
      window.input = window.doc.getElementById("m-search-input");
      window.schList = window.doc.getElementById("m-search");
    } else if (/^虾米音乐[\w]*/g.test(siteTitle)) {
      window.srchBtn = document.querySelector(".iconfont");
      window.input = document.querySelector(".search > input");
      window.schList = document.querySelector(".table-container tbody");
      window.colloctMenu = document.querySelector('.table-container tbody tr:first-of-type td:last-of-type .ops-right .ops-item:last-of-type');
      window.colloctMenu.click(); //triggle loading of playlist

      //document.querySelector(".music-context-menu nav").style["margin-left"] = "160px";
      //document.querySelector(".music-context-menu nav").style["margin-top"] = "233px";
    }

    // The textarea for input json data
    window.txtAr = document.getElementById("trackData");
    // Total count
    window.ttc = document.getElementById("ttc");
    // Remaining count
    window.rm = document.getElementById("rm");
    // Not found count
    window.nf = document.getElementById("nf");

    // Title text box
    window.cntTck = document.getElementById("tck");
    // Artist text box
    window.cntAtt = document.getElementById("att");
    // Album text box
    window.cntAbm = document.getElementById("abm");
    // Track duration
    window.tckDura = document.getElementById("tckDura");

    // Not found panel
    window.nfPnl = document.getElementById("nfPnl");

    // Observe dom changes on the search list
    try {
      mutationObserver.observe(window.schList, {
        attributes: true,
        characterData: true,
        childList: true,
        subtree: true,
        attributeOldValue: true,
        characterDataOldValue: true
      });
    } catch (e) { };
  }
  // Manully put current song to no found list
  window.setNotFound = function () {
    if (currentTrack) {
      tracksNotFound.push(currentTrack);
      window.nf.innerText = tracksNotFound.length;
    }
  };
  // Not found button callback
  window.showNotFound = function () {
    if (window.nfPnl.style.visibility == "hidden") {
      let items = "";
      tracksNotFound.forEach((v, i, a) => {
        items += `<div style="margin-bottom: 5px; padding-bottom: 5px; border-bottom: dotted 1px #cccccc;">${v.title}-${v.artist}-${v.album}</div>`;
      });
      if (window.nfPnl.firstChild) {
        window.nfPnl.removeChild(window.nfPnl.firstChild);
      }
      window.nfPnl.insertAdjacentHTML("beforeend", `<div>${items}</div>`);
      window.nfPnl.style.visibility = "visible";
    } else {
      window.nfPnl.style.visibility = "hidden";
    }
  };
  // Load button callback
  window.ld = function () {
    initCmp();
    try {
      tracks = JSON.parse(window.txtAr.value);
    } catch (error) {
      tracks = [];
    }

    // Initialize all the varibles
    totalTracks = tracks.length;
    isLooping = false;
    isCtrlBtn = false;
    currentTrack = null;
    if (/网易云音乐/g.test(siteTitle)) {
      tracks.reverse();
    }
    trackCache = [];
    tracksNotFound = [];
    window.nf.innerText = tracksNotFound.length;
    window.rm.innerText = window.ttc.innerText = tracks.length;
    window.cntTck.value = "";
    window.cntAtt.value = "";
    window.cntAbm.value = "";
    window.tckDura.innerText = "0:00";
    window.input.value = "";
  };

  function fillContent(track) {
    window.rm.innerText = tracks.length; //This info is not from track
    window.cntTck.value = track.title;
    window.cntAtt.value = track.artists;
    window.cntAbm.value = track.album;
    window.tckDura.innerText = track.duration;

    if (/网易云音乐/g.test(siteTitle)) {
      window.input.value = `${track.title} ${track.artists} ${track.album}`;
    } else if (/^虾米音乐[\w]*/g.test(siteTitle)) {
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
      nativeInputValueSetter.call(window.input, `${track.title} ${track.artists} ${track.album}`);
      const ev2 = new Event('input', {
        bubbles: true
      });
      window.input.dispatchEvent(ev2);
    }

  }
  // Search button callback
  window.sch = function () {
    if (isCtrlBtn) {
      window.srchBtn.click();
    } else {
      if (window.nxtTrack()) {
        window.srchBtn.click();
      }
    }
    isCtrlBtn = false;
  };

  window.preTrack = function () {
    if (trackCache.length == 0) {
      if (tracks.length == 0) {
        alert("没有数据！");
        return;
      } else { // At the start of track array
        if (currentTrack) {
          trackCache.push(currentTrack);
          currentTrack = null;
        }
        trackCache = trackCache.concat(tracks);
        tracks = [];
      }
    }

    if (!isCtrlBtn) {
      isCtrlBtn = true;
    }

    if (currentTrack) {
      tracks = [currentTrack].concat(tracks);
    }
    currentTrack = trackCache.pop();

    fillContent(currentTrack);
  };

  window.nxtTrack = function () {
    if (tracks.length == 0) {
      if (trackCache.length == 0) {
        alert("没有数据！");
        return false;
      }
      // Reaches the end of track array, set all the arrays to the firstly loaded state
      else if (currentTrack) {
        trackCache.push(currentTrack);
        tracks = trackCache;
        currentTrack = null;
        trackCache = [];
      }
    }

    // Only change the state of isSchBtn if there are actrual data loaded upon clicking
    if (!isCtrlBtn) {
      isCtrlBtn = true;
    }

    if (currentTrack) {
      trackCache.push(currentTrack);
    }
    currentTrack = tracks.shift();

    fillContent(currentTrack);
    return true;
  };

  window.jumpTo = () => {
    if (tracks.length == 0 && trackCache.length == 0) {
      alert("没有数据！");
      return;
    }

    let jumpNum = 0;
    try {
      jumpNum = parseInt(prompt("跳到第几首？", 0));
    } catch (error) { }
    jumpNum -= 1;

    if (!isCtrlBtn) {
      isCtrlBtn = true;
    }

    if (currentTrack) {
      trackCache.push(currentTrack);
    }
    tracks = trackCache.concat(tracks);
    if (jumpNum <= 0) {
      trackCache = [];
      currentTrack = tracks.shift();
    } else if (jumpNum >= totalTracks - 1) {
      trackCache = trackCache.concat(tracks);
      tracks = [];
      currentTrack = trackCache.pop();
    } else {
      trackCache = tracks.slice(0, jumpNum);
      tracks = tracks.slice(jumpNum);
      currentTrack = tracks.shift();
    }
    fillContent(currentTrack);
  }

  // Add to playlist button callback
  window.fv = function () {
    let favBtn;
    if (/网易云音乐/g.test(siteTitle)) {
      const fRow = window.doc.querySelector(".item.f-cb.h-flag");
      if (!fRow) {
        return;
      }
      favBtn = fRow.firstChild.nextSibling.nextSibling.firstChild.firstChild.nextSibling;
      favBtn.click();
    } else if (/^虾米音乐[\w]*/g.test(siteTitle)) {
      document.querySelector('.table-container tbody tr:first-of-type td:last-of-type .ops-right .ops-item:last-of-type').click();
    }
  };

  function initUI() {
    let el = document.createElement("div");
    el.setAttribute(
      "style",
      `
          position: fixed;
          float: right;
          display: inline;
          width: 280px;
          height: 320px;
          top: 120px;
          right: 50px;
          box-shadow: 0px 0px 50px 5px rgba(194,12,12,0.1);
          border-radius: 5px;
          background: #ffffff;
          `
    );
    el.insertAdjacentHTML(
      "beforeend",
      `
          <div style="text-align: center; line-height: 2.5; background: #232323; color: white; border-radius: 5px 5px 0 0;font-weight: 600;">
              <div title="显示未找到歌曲" onclick="showNotFound();" style="width: 10px; height: 10px; background: rgba(192,12,12,1); border-radius: 15px; display: inline-block; position: absolute; left: 10px; top: 10px; cursor: pointer;"></div>
              <div title="加入未找到歌曲" onclick="setNotFound();" style="width: 10px; height: 10px; background: rgba(192,12,12,1); border-radius: 15px; display: inline-block; position: absolute; left: 25px; top: 10px; cursor: pointer;"></div>
              <span>网易云音乐歌单导入助手</span>
              <div title="歌曲时长" id="tckDura" style="height: 10px; color: rgba(192,12,12,1); display: inline-block; position: absolute; right: 10px;">0:00</div>
          </div>
          <div style="display: flex; flex-direction: column; align-items: center; line-height: 2; padding: 0 25px 0 25px;">
              <div>
                  <div>歌曲：</div><input id="tck" type="input" style="line-height: 2; border-radius: 3px; border: solid #cccccc 1px; padding: 0 5px 0 5px; box-shadow: inset 0px 2px 5px 0px rgba(166,166,166,0.6);"/>
              </div>
              <div >
                  <div>艺术家：</div><input id="att" type="input" style="line-height: 2; border-radius: 3px; border: solid #cccccc 1px; padding: 0 5px 0 5px; box-shadow: inset 0px 2px 5px 0px rgba(166,166,166,0.6);"/>
              </div>
              <div>
                  <div>专辑：</div><input id="abm" type="input" style="line-height: 2; border-radius: 3px; border: solid #cccccc 1px; padding: 0 5px 0 5px; box-shadow: inset 0px 2px 5px 0px rgba(166,166,166,0.6);"/>
              </div>
              <div style="width: 100%; text-align: center;">
                  <span id="preBtn" onclick="preTrack();" style="background: #efefef;padding: 2px 5px;box-shadow: 1px 1px 1px 0.5px #777;border-radius: 5px;"><a style="border-top: solid 1px rgb(192, 12, 12); padding: 1.5px 1.5px; transform: rotate(-45deg); display: inline-block; border-left: solid 1px rgb(192, 12, 12); vertical-align: middle;"></a><a style="border-top: solid 1px rgb(192, 12, 12); padding: 2px 2px; transform: rotate(-45deg); display: inline-block; border-left: solid 1px rgb(192, 12, 12); vertical-align: middle;"></a></span>
                  <input type="button" value="加载" onclick="ld();" style="width: 40px; height: 25px; border-radius: 5px; margin: 5px;font-size:9px;"/>
                  <input type="button" value="搜索" onclick="sch();" style="width: 40px; height: 25px; border-radius: 5px; margin: 5px;font-size:9px;"/>
                  <input type="button" value="导入到" onclick="fv();" style="width: 40px; height: 25px; border-radius: 5px; margin: 5px;font-size:9px;"/>
                  <span id="nxtBtn" onclick="nxtTrack();" style="background: #efefef;padding: 2px 5px;box-shadow: 1px 1px 1px 0.5px #777;border-radius: 5px;"><a style="border-top: solid 1px rgb(192, 12, 12); padding: 2px 2px; transform: rotate(45deg); display: inline-block; border-right: solid 1px rgb(192, 12, 12); vertical-align: middle;"></a><a style="border-top: solid 1px rgb(192, 12, 12); padding: 1.5px 1.5px; transform: rotate(45deg); display: inline-block; border-right: solid 1px rgb(192, 12, 12); vertical-align: middle;"></a></span>
              </div>
              <div style="background: #eeeeee; width: 100%; height: 60px; padding: 8px;border: solid 0.5px #aaaaaa;">
                  <textarea id="trackData" style="width: 100%; height: 100%; left: -4px; top: -4px; position: relative;box-shadow: inset 1px 1px 5px 1px rgba(166,166,166,0.6);padding: 3px;"></textarea>
              </div>
          </div>
          <div style="text-align: center; line-height: 2; background: #232323; color: white; border-radius: 0 0 5px 5px; bottom: 0; position: absolute; width: 100%;font-size: smaller;">
              <span title="跳转到" onclick="jumpTo();" style="border-right: solid 1px;padding-right: 5px;cursor: pointer">共：<span id="ttc">0</span>首<a style="	padding: 2px; background: rgba(255,12,12,1); display: inline-block; border-radius: 45px; position: absolute; bottom: 3px; left: 67px;"></a></span>
              <span style="border-right: solid 1px; padding: 0 5px 0 3px;">剩余：<span id="rm">0</span>首</span>
              <span style="padding-left: 3px;">未找到：<span id="nf">0</span>首</span>
          </div>
          <div id="nfPnl" style="height: 260px; background: #ffffff; position: relative; top: -259px; padding: 5px 25px; visibility:hidden;overflow: auto;"><div></div></div>
          `
    );
    document.body.appendChild(el);
  }
  initUI();
})();